package com.book.utils.JWT;

import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.book.bean.User;
import com.book.service.UserService;
import com.book.utils.Exception.CustomException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class JwtInterceptor implements HandlerInterceptor {
    private static final Logger log = LoggerFactory.getLogger(JwtInterceptor.class);

    @Resource
    private UserService userService;  //用户 服务类

    @Override
    public boolean preHandle(HttpServletRequest request , HttpServletResponse response,Object handle){
        String token = request.getHeader("token");//获取请求头
        if(StrUtil.isBlank(token)){
            token = request.getParameter("token");//如果请求头里面没有，则在参数里面拿
        }
        if(StrUtil.isBlank(token)){
            throw new CustomException("无token，请重新登陆");  //使用自定义异常处理
        }
        String adminId;
        User user;
        try{
            adminId = JWT.decode(token).getAudience().get(0);
            //根据token中的userId查询数据库
            user = userService.findById(Integer.parseInt(adminId));
        }catch (Exception e){
            String errMsg = "token验证失败，请重新登陆！！";
            log.error(errMsg+",token="+token,e);
            throw new CustomException(errMsg);
        }
        if(user == null){
            throw new CustomException("用户名不存在，请重新登陆");
        }
        try{
            JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(user.getPassword())).build();
            jwtVerifier.verify(token);
        }catch (JWTVerificationException e){
            throw new CustomException("用户名不存在，请重新登陆");
        }
        return true;
    }
}
